package com.freesky.biz.abchina.api;


import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import com.freesky.common.core.domain.AjaxResult;

import com.freesky.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.util.*;

/**
 * 有福分接口
 * 测试环境的活动：
 * 活动id：4be393d89e4c48f79905ff7800afbc4b
 * 权益id：854077c320bb41fea6dcdc76a8de503f
 * 机构号：DL1572125607620517888
 */
@Service
@Slf4j
public class AbChinaCoupon {

    private static Logger logger = LoggerFactory.getLogger(AbChinaCoupon.class);

    @Autowired
    private AbChinaConfiguration abChinaConfiguration;

    //根据⼿机号获取客户号
    public AjaxResult getCustIdByPhone(String mobile){
        try{
            String url = abChinaConfiguration.getRightsPrefixUrl() + "/api/v1/user/getCustIdByPhone";
            long timestamp = System.currentTimeMillis();
            logger.info("getCustIdByPhone:"+url);

            Map<String,Object> bodyMap = new HashMap<>();
            bodyMap.put("phone",mobile);

            String bodyString = JSON.toJSONString(bodyMap);
            String signParams = abChinaConfiguration.getRightsToken() +"|" + bodyString +"|"+ String.valueOf(timestamp);
            String sighSHA256 = DigestUtil.sha256Hex(signParams);

            logger.info("【bodyString:"+bodyString+"】,signParams:【"+ signParams+"】sighSHA256："+sighSHA256);

            SymmetricCrypto sm4 = SmUtil.sm4(HexUtil.decodeHex(abChinaConfiguration.getRightsToken()));
            String bodyEnc = sm4.encryptHex(bodyString);

            Map<String,Object> reqMap = new HashMap<>();
            reqMap.put("appId",abChinaConfiguration.getRightsAppId());
            reqMap.put("timestamp",timestamp);
            reqMap.put("sign",sighSHA256);
            reqMap.put("data",bodyEnc);

            logger.info("getCustIdByPhone Req:"+JSON.toJSONString(reqMap));
            String result = HttpRequest.post(url)
                    .header(Header.USER_AGENT, "Chrome")
                    .header(Header.CONTENT_TYPE,"application/json")
                    .charset("utf8")
                    .body(JSON.toJSONString(reqMap))
                    .timeout(10000)
                    .execute().body();
            logger.info("getCustIdByPhone Resp:"+result);

            JSONObject jsonObject = JSON.parseObject(result);
            String retCode = jsonObject.getString("retcode");
            if("0".equalsIgnoreCase(retCode)){
                String data = jsonObject.getString("data");
                String respBody = sm4.decryptStr(data);
                logger.info("getCustIdByPhone respBody:"+respBody);
                String custId = JSONObject.parseObject(respBody).getString("custId");
                return AjaxResult.success("成功",custId);
            } else {
                return AjaxResult.error(jsonObject.getString("retmsg"));
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            return AjaxResult.error("请求接口异常!");
        }
    }

    //下单查询
    public AjaxResult userQuery(String billNo){
        try{
            String url = abChinaConfiguration.getRightsPrefixUrl() + "api/v1/user/orderRequest";

            long timestamp = System.currentTimeMillis();

            Map<String,Object> bodyMap = new HashMap<>();

            bodyMap.put("billNo", billNo);

            String bodyString = JSON.toJSONString(bodyMap);
            String signParams = abChinaConfiguration.getRightsToken() +"|" + bodyString +"|"+ String.valueOf(timestamp);
            String sighSHA256 = DigestUtil.sha256Hex(signParams);

            logger.info("【bodyString:"+bodyString+"】,signParams:【"+ signParams+"】sighSHA256："+sighSHA256);

            SymmetricCrypto sm4 = SmUtil.sm4(HexUtil.decodeHex(abChinaConfiguration.getRightsToken()));

            String bodyEnc = sm4.encryptHex(bodyString);

            Map<String,Object> reqMap = new HashMap<>();
            reqMap.put("appId",abChinaConfiguration.getRightsAppId());
            //reqMap.put("appId","3c1d02edb6bc447dbf84a4a25f8ea3ee");
            reqMap.put("timestamp",timestamp);
            reqMap.put("sign",sighSHA256);
            reqMap.put("data",bodyEnc);

            logger.info("req:"+JSON.toJSONString(reqMap));
            String result = HttpRequest.post(url)
                    .header(Header.USER_AGENT, "Chrome")
                    .header(Header.CONTENT_TYPE,"application/json")
                    .charset("utf8")
                    .body(JSON.toJSONString(reqMap))
                    .timeout(10000)
                    .execute().body();
            logger.info("resp:"+result);
            JSONObject jsonObject = JSON.parseObject(result);
            String retCode = jsonObject.getString("retcode");
            if("0".equalsIgnoreCase(retCode)){
                String data = jsonObject.getString("data");
                String respBody = sm4.decryptStr(data);
                logger.info("resp decrypt:"+respBody);
                return AjaxResult.success("成功",respBody);
            } else {
                return AjaxResult.error(jsonObject.getString("retmsg"));
            }

        } catch (Exception ioe){
            ioe.printStackTrace();
            return AjaxResult.error("请求接口异常!");
        }
    }

    public static void main(String args[]) throws Exception, InvalidAlgorithmParameterException {
        AbChinaCoupon abChinaCoupon = new AbChinaCoupon();
        System.out.println(JSON.toJSONString(abChinaCoupon.getCustIdByPhone("18650992221")));
    }

}
